﻿using UnityEngine;
using UnityEngine.UI;

using System.Collections.Generic;
namespace VFramework{
	
	public class VUIVerticalListView : VUIPopWindow {

		public ScrollRect scrollRect;
		public Image itemContainer;
		public Image item;


		public delegate void ItemUpdateHandler(Image item, object obj);
		public event ItemUpdateHandler uhander = null;
		private List<Image> itemNodes = new List<Image> ();

		void Start () {
			base._start ();
		}


		public void appedItem(object obj){
			item.gameObject.SetActive (true);

			float h1 = item.rectTransform.sizeDelta.y;
			float h2 = (itemNodes.Count + 1) * h1;

			setBgHeight (h2);

			Image nitem = GameObject.Instantiate (item.gameObject).GetComponent<Image> ();
			nitem.transform.SetParent (itemContainer.transform);
			nitem.transform.localScale = Vector3.one;
			nitem.transform.localPosition = new Vector3 (0, -itemNodes.Count * h1 - h1 * 0.5f);

			itemNodes.Add (nitem);

			updateItemByObj (nitem, obj);
			item.gameObject.SetActive (false);
		}

		void setBgHeight (float height)
		{
			itemContainer.rectTransform.sizeDelta = new Vector2 (20, height);
		}

		public void clean(){
			foreach (Image i in itemNodes) {
				GameObject.DestroyObject (i.gameObject);
			}

			itemNodes.Clear ();
			item.gameObject.SetActive (false);
			setBgHeight (0);
		}

		private void updateItemByObj(Image item, object obj){
			if (uhander != null) {
				uhander.Invoke (item, obj);
			}
		}

		public Image getItem(int index){
			return itemNodes [index];
		}
	}

}